package com.koron.system.staff.service.impl;

import com.koron.bean.app.AppBean;
import com.koron.bean.base.BaseQueryBean;
import com.koron.bean.base.Response;
import com.koron.bean.system.org.OrgBean;
import com.koron.bean.system.staff.StaffBean;
import com.koron.bean.system.staff.dto.OutStaffApplyBean;
import com.koron.bean.system.staff.dto.OutStaffAuditBean;
import com.koron.bean.system.staff.dto.OutStaffBean;
import com.koron.bean.system.staff.po.AppUserPo;
import com.koron.bean.system.staff.vo.EamUser;
import com.koron.bean.util.RedisUtils;
import com.koron.bean.util.UUIDUtils;
import com.koron.common.core.business.system.MyRSAUtil;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.CheckPassword;
import com.koron.common.core.util.PhoneFormatCheckUtils;
import com.koron.common.core.util.sms.IMobileMessageSender;
import com.koron.common.core.util.sms.MobileMessageVO;
import com.koron.system.app.service.AppService;
import com.koron.system.common.util.MD5Utils;
import com.koron.system.org.service.OrgService;
import com.koron.system.staff.mapper.OutStaffMapper;
import com.koron.system.staff.service.OutStaffService;
import com.koron.system.staff.service.StaffService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OutStaffServiceImpl
 * @description
 * @Author zhouj
 * @Date 2021/7/7 16:37
 */
@Transactional
@Service
public class OutStaffServiceImpl implements OutStaffService {

    @Autowired
    OutStaffMapper outStaffMapper;

    @Autowired
    IMobileMessageSender iMobileMessageSender;

    @Autowired
    AppService appService;

    @Autowired
    OrgService orgService;

    @Autowired
    StaffService staffService;

    @Override
    public Response regist(OutStaffBean bean) {
        int i = 0;

        if (StringUtils.isNotEmpty(bean.getId())) {
            return Response.fail();
        }

        //校验验证码
        String verity = (String) RedisUtils.hget("eam-service-system-VerifyCode", bean.getPhone());

        if (StringUtils.isEmpty(verity)) {
            return Response.fail("验证码过期");
        }

        if (StringUtils.isEmpty(bean.getVerityCode()) || !StringUtils.equals(verity, bean.getVerityCode())) {
            return Response.fail("验证码失效,请重新获取");
        }

        String phone = bean.getPhone();
        //校验手机号合理性
        if (!PhoneFormatCheckUtils.isPhoneLegal(phone)) {
            return Response.fail("手机号不正确");
        }
        //校验水司存在性
        AppBean appBean = new AppBean();
        appBean.setId(bean.getAppid());
        AppBean appBean1 = appService.querySingleApp(appBean);
        if (appBean1 == null) {
            return Response.fail("水司不存在");
        }

        //校验组织存在性
        String[] split = bean.getOrgId().split(",");
        List<String> orgIds = Arrays.asList(split);
        OrgBean orgBean = new OrgBean();
        for (String orgId : orgIds) {
            orgBean.setId(orgId);
            OrgBean orgBean1 = orgService.querySingleOrg(orgBean);
            if (orgBean1 == null) {
                return Response.fail("所选组织不存在");
            }
        }

        //校验账号唯一性
        StaffBean staffBean = staffService.querySingleStaffInfoByAccount(bean.getPhone());
        if (staffBean != null) {
            return Response.fail("账号已存在");
        }

        //校验密码  1.先加密传输 2.是否符合规则
        //私钥解密后,再 校验是否合格
        String decrypt_pw = null;
        try {
            decrypt_pw = MyRSAUtil.decrypt(bean.getPassword());
        } catch (Exception e) {
            return Response.fail("密码未正确加密");
        }

        if (!CheckPassword.checkPassword(decrypt_pw)) {
            //校验失败
            return Response.fail("密码必须包含字母,数字,特殊字符");
        }

        bean.setId(UUIDUtils.getUuid());
        bean.setApplyTime(new Date());
        String str = MD5Utils.md5(decrypt_pw);
        bean.setPassword(str);

        i = outStaffMapper.insert(bean);
        /*OutStaffApplyBean outStaffApplyBean = outStaffMapper.queryByPhone(bean.getPhone());
        if (Objects.isNull(outStaffApplyBean)) {
            i = outStaffMapper.insert(bean);
        } else {
            return Response.fail("手机号已申请过");
        }*/
        return Response.ok(i);
    }

    @Override
    public int update(OutStaffBean outStaffBean) {
        int i = 0;
        if (StringUtils.isNotEmpty(outStaffBean.getId())) {
            outStaffBean.setApplyTime(new Date());
            i = outStaffMapper.update(outStaffBean);
        }
        return i;
    }

    @Override
    public List<OutStaffApplyBean> queryAuditList(OutStaffApplyBean bean, BaseQueryBean queryBean) {
        EamUser eamUser = ThreadLocalContext.get();
        List<OutStaffApplyBean> outStaffApplyBeans = outStaffMapper.queryAuditListByJurisdiction(bean, eamUser.getAccount(), queryBean);
        if (CollectionUtils.isNotEmpty(outStaffApplyBeans)) {
            outStaffApplyBeans.forEach(p -> p.setPassword(null));
        }
        return outStaffApplyBeans;
    }

    @Override
    public Response audit(EamUser user, OutStaffAuditBean outStaffAuditBean) {

        Integer approvalStatus = outStaffAuditBean.getApprovalStatus();
        String approvalContent = outStaffAuditBean.getApprovalContent();

        if (approvalStatus == null) {
            return Response.fail("请选择审核意见");
        }

        List<OutStaffApplyBean> outStaffApplyBeans = outStaffMapper.queryAuditList(outStaffAuditBean.getOutStaffApplyId());
        if (CollectionUtils.isEmpty(outStaffApplyBeans)) {
            return Response.fail("没有找到该条数据");
        }
        Date date = new Date();
        outStaffApplyBeans.forEach(p -> {
            p.setApprovalStatus(approvalStatus);
            p.setApprovalContent(approvalContent);

            p.setApprovalBy(user.getAccount());
            p.setApprovalByName(user.getName());
            p.setApprovalTime(date);

        });

        int i = outStaffMapper.patchAudit(outStaffApplyBeans);
        //审核通过 将信息加入到用户表
        List<AppUserPo> staffBeanList = new ArrayList<>();
        outStaffApplyBeans.forEach(p -> {
            AppUserPo userPo = new AppUserPo();
            BeanUtils.copyProperties(p, userPo);
            staffBeanList.add(userPo);
        });

        staffService.batchInUpUser(ThreadLocalContext.get(), staffBeanList);
        //审核后,发送短信
        int m = sendApprovalMessage(outStaffApplyBeans);
        return Response.ok(i);
    }

    @Override
    public int delete(String id) {
        return outStaffMapper.delete(id);
    }

    @Override
    public int deleteIds(List<String> ids) {
        return outStaffMapper.deleteIds(ids);
    }

    @Override
    public int sendPhoneMessage(String phone) {
        return sendPhoneMessage(phone, "eam-service-system-VerifyCode", " EAM系统注册短信验证码: ");
    }

    @Override
    public int sendPhoneMessage(String phone, String key, String messageContent) {
        //校验验证码
        String verity = (String) RedisUtils.hget(key, phone);
        if (StringUtils.isNotEmpty(verity)) {
            throw new IllegalArgumentException("不允许频繁发送验证码");
        }
        String generateCode = generateCode();

        MobileMessageVO message = new MobileMessageVO();
        message.setReceiverPhone(phone);
        message.setMessageContent(messageContent + generateCode + " 一分钟有效");
        int i = iMobileMessageSender.sendSingleMessage(message);
        if (i == 1) {
            RedisUtils.hset(key, phone, generateCode, 60);
        }
        return i;
    }

    public String generateCode() {
        long codeL = System.nanoTime();
        String codeStr = Long.toString(codeL);
        return codeStr.substring(codeStr.length() - 6);
    }

    public int sendApprovalMessage(List<OutStaffApplyBean> beanList) {

        List<MobileMessageVO> mobileMessageVOS = new ArrayList<>();
        beanList.forEach(p -> {
            MobileMessageVO message = new MobileMessageVO();
            message.setReceiverPhone(p.getPhone());
            String approvalInfo;
            switch (p.getApprovalStatus()) {
                case 1:
                    approvalInfo = "同意";
                    break;
                case -1:
                    approvalInfo = "拒绝";
                    break;
                default:
                    approvalInfo = "待审核";
                    break;
            }

            if (p.getApprovalStatus() == -1) {
                message.setMessageContent("\n EAM系统注册审核通知意见: " + approvalInfo + "\n 拒绝原因:" + p.getApprovalContent() + "\n 审核人:" + p.getApprovalByName());
            } else {
                message.setMessageContent("\n EAM系统注册审核通知意见: " + approvalInfo + "\n 审核人:" + p.getApprovalByName());
            }
            mobileMessageVOS.add(message);
        });

        return iMobileMessageSender.sendMessage(mobileMessageVOS);
    }

}
